package com.cf.web.servlet;

import com.cf.dao.UserDao;
import com.cf.dao.impl.UserDaoImpl;
import com.cf.web.util.FTPUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.UUID;

@WebServlet("/uploadImage")
@MultipartConfig
public class ImageUploadServlet extends HttpServlet {
    // 使用适当的类来保存图片 URL 到数据库
    private UserDao userdao =new UserDaoImpl();
    public static int userId;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // GET 请求可以根据需求返回上传页面等
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("application/json; charset=UTF-8");
        userId = Integer.parseInt(request.getParameter("userid"));

        // 获取上传的图片文件
        Part filePart = request.getPart("image");  // "image" 是前端表单中的文件字段名
        if (filePart == null) {
            System.out.println("上传文件字段为空");
            response.getWriter().write("{\"success\": false, \"message\": \"上传的文件字段为空\"}");
            return;
        }

        // 生成唯一的文件名，避免文件名冲突
        String originalFileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString();
        String uniqueFileName = UUID.randomUUID().toString() + "_" + originalFileName;
        System.out.println("上传的文件名: " + uniqueFileName);

        // 设置本地上传路径，避免路径穿越
        String localFilePath = getServletContext().getRealPath("/uploads/" + uniqueFileName);
        System.out.println("本地文件路径: " + localFilePath);

        try {
            // 创建目录（如果不存在）
            File file = new File(localFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }

            // 写入文件到本地
            filePart.write(localFilePath);
            System.out.println("文件写入成功到本地");

            // 设置 FTP 上传目录（可以根据需要设置）
            String remoteDir = "/img";  // FTP 服务器上的目录
            System.out.println("准备上传到 FTP 服务器，远程目录: " + remoteDir);

            // 上传到 FTP 服务器
            boolean uploadSuccess = FTPUtil.uploadFile("123.60.90.253", 21, "huaban", "k3AEN7StRmw73m5n", localFilePath, remoteDir);
            if (uploadSuccess) {
                System.out.println("FTP 上传成功");

                // 上传成功后保存图片 URL 到数据库
                String imageUrl = "https://123.60.90.253:31541/down/HrszjhtSYXgf" + "?" + "fname=" + "/" + uniqueFileName;
                System.out.println("上传的图片 URL: " + imageUrl);

                boolean saveSuccess = userdao.saveImageUrlToDatabase(imageUrl, userId);
                if (saveSuccess) {
                    response.getWriter().write("{\"success\": true, \"message\": \"上传成功\", \"imageUrl\": \"" + imageUrl + "\"}");
                    request.getSession().setAttribute("avatar", imageUrl);
                    System.out.println("图片 URL 保存到数据库成功");
                } else {
                    response.getWriter().write("{\"success\": false, \"message\": \"保存图片 URL 到数据库失败\"}");
                    System.out.println("保存图片 URL 到数据库失败");
                }
            } else {
                response.getWriter().write("{\"success\": false, \"message\": \"FTP 上传失败\"}");
                System.out.println("FTP 上传失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            response.getWriter().write("{\"success\": false, \"message\": \"文件上传失败，原因: " + e.getMessage() + "\"}");
            System.out.println("文件上传异常: " + e.getMessage());
        }
    }
}
